<template>
  <div class="main-container">
    <el-row :gutter="5">
      <el-col v-for="(item, adindex) of dataList" :key="adindex" :xs="24" :sm="12" :md="adindex == 0 ? 12 : 6"
        class="item-wrapper">
        <DataItem :data-model="item">
          <!-- <template v-if="adindex === 0" #extra="{ extra }">
            <div class="margin-top">
              <div class="text-gray">
                较昨日新增：{{ extra.data }}
                <i class="el-icon-caret-top text-green"></i>
              </div>
              <div class="text-gray margin-top-sm">
                较上周新增：{{ extra.data1 }}
                <i class="el-icon-caret-top text-blue"></i>
              </div>
            </div>
          </template>
          <template v-else-if="adindex === 1" #extra="{ extra }">
            <div class="margin-top" style="position: relative">
              <div class="text-gray">
                较昨日新增：{{ extra.data }}
                <i class="el-icon-caret-top text-green"></i>
              </div>
              <div class="text-gray margin-top-sm">
                较上周新增：{{ extra.data1 }}
                <i class="el-icon-caret-top text-blue"></i>
              </div>
              <div class="stack-avatar-wrapper">
                <StackAvatar />
              </div>
            </div>
          </template>
          <template v-else-if="adindex === 2" #extra="{ extra }">
            <el-progress :text-inside="true" :stroke-width="15" :percentage="extra.data" status="exception" />
          </template>
          <template v-else-if="adindex === 3" #extra>
            <OrderChart ref="mOrderChart" />
          </template> -->
        </DataItem>
      </el-col>
    </el-row>
    <el-row :gutter="5" class="margin-top-xs">
      <!-- <el-col :xs="24" :sm="24" :md="6">
        <div class="flex flex-direction">
          <SalesChart ref="salesChart" />
          <StudentChart ref="studentChart" class="margin-top-xs" />
        </div>
      </el-col> -->
      <el-col :xs="24" :sm="24" :md="24" class="map-margin-tb">
        <div>
          <!-- <SchoolChart ref="schoolChart" /> -->
          <el-card :body-style="{ padding: '0px' }" style="padding-left: 0 10px;" shadow="always">
            <template #header>
              <span class="text-bold text-sm">
                <img src="@/assets/img/lj.png" alt="" srcset="" style="width:20px;height:20px;">
                <i class="el-icon-s-opportunity text-blue"></i>
                行事历
                <el-button style=" padding: 3px 0" type="text" @click="addTask">添加任务</el-button>
              </span>
              <el-button @click="getNextWeek" style="float: right;padding-left: 20px;cursor: pointer;"
                type="text">下一周</el-button>
              <el-button @click="getCurWeek" style="float: right;cursor: pointer;padding-left: 20px;"
                type="text">本周</el-button>
              <el-button @click="getLastWeek" style="float: right;cursor: pointer;" type="text">上一周</el-button>

            </template>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="6" :lg="6" :body-style="{ border: 0 }">
                <el-card class="box-card" style="height: 605px;">
                  <div slot="header" class="clearfix">
                    <span>今日工作安排</span>
                    <span style="float: right;">待办:{{ num1 ? num1 : 0 }}</span>
                    <span style="float: right;padding: 0 20px;">已完成:{{ num2 ? num2 : 0 }}</span>
                    <!-- <el-button style="float: right; padding: 3px 0" type="text" @click="addTask">添加任务</el-button> -->
                  </div>
                  <div v-for="(o, i) in getCurDayList" :key="i" class="text item">
                    <div v-if="o.finish == 0"><span> {{ '待办任务 ' }}：</span>{{ o.data }}</div>
                    <div v-if="o.finish == 1"><span style="color: #409eff;"> {{ '已完成任务 ' }}：</span>{{ o.data }}</div>
                  </div>
                  <!-- <div style="position: absolute;bottom: 10px;display: flex;">
                    <el-input v-model="ruleForm.data" placeholder="请输入内容" style="width: 300px;"></el-input>
                    <span style="width:20px;"></span>
                    <el-button @click="submitForm" style="background-color: #ebb563;color: #fff;">添加</el-button>
                  </div> -->
                </el-card>
              </el-col>
              <el-col :xs="24" :sm="12" :md="6" :lg="6" v-for="(item, index) in months" :body-style="{ border: 0 }"
                :key="index" style="margin-bottom: 5px;">
                <el-card shadow="always" class="box-card" style="height: 300px;">
                  <template #header>
                    <div class="card-header">
                      <span v-if="item.isCurDate" style="color:#409eff">{{ item.week }}</span>
                      <span v-else>{{ item.week }}</span>
                      <span style="float: right;">{{ item.date }}</span>
                    </div>

                  </template>

                  <div style="max-height: 200px;overflow: auto;">
                    <div v-for="(items, index2) in item.weekDayAsk" :key="index2" style="margin-bottom: 20px;">
                      <div style="display: inline-block;">{{ index2 + 1 }}.{{ items.data }}</div>
                      <div style="display: inline-block;float: right;">
                        <el-button type="text" size="mini" icon="el-icon-success" style="cursor: pointer;"
                          @click="edit(index, items.id)">完成</el-button>
                        <el-button type="text" size="mini" icon="el-icon-delete" style="cursor: pointer;"
                          @click="del(index, items.id)" v-if="items.finish == 0">删除</el-button>
                      </div>
                    </div>
                  </div>

                </el-card>
              </el-col>

            </el-row>
            <!-- <el-row :gutter="20" style="margin-bottom: 30px;">
              <el-col :span="8" v-for="(item) in timrRange3" :body-style="{ border: 0 }" :key="item.value">
                <el-card shadow="always" class="box-card">
                  <template #header>
                    <div class="card-header">
                      <span v-if="item.time == nowDateTime" style="color:#409eff">{{ item.value }}</span>
                      <span v-else>{{ item.value }}</span>
                      <div class="demo-progress">
                        <el-progress :percentage="50" />
                      </div>
                    </div>
                  </template>
                  <div style="height: 100px;text-align: center;cursor: pointer;" @click="addEvent">
                    <img src="@/assets/img/draft-fill.png" alt="" style="width:48px;height:48px;">
                    <div>添加记事</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8" v-for="(item) in timrRange4" :body-style="{ border: 0 }" :key="item.value">
                <el-card shadow="always" class="box-card">
                  <template #header>
                    <div class="card-header">
                      <span style="font-size: 10px;">{{ item.value }}</span>
                      <div class="demo-progress">
                        <el-progress :percentage="50" />
                      </div>
                    </div>
                  </template>
                  <div style="height: 100px;text-align: center;cursor: pointer;" @click="addEvent">
                    <img src="@/assets/img/draft-fill.png" alt="" style="width:48px;height:48px;">
                    <div>添加记事</div>
                  </div>
                </el-card>
              </el-col>
            </el-row> -->
          </el-card>
        </div>
      </el-col>
      <!-- <el-col :xs="24" :sm="24" :md="6">
        <div class="flex flex-direction">
          <EnrollmentChannelsChart ref="enrollmentChannelsChart" />
          <DepartmentChart ref="departmentChart" class="margin-top-xs" />
        </div>
      </el-col> -->
    </el-row>
    <!-- <el-row :gutter="5" class="margin-top-xs">
      <el-col :span="24">
        <FullYearSalesChart ref="fullYearSalesChart" />
      </el-col>
    </el-row> -->

    <el-dialog :title="dialogVisibleTitle" :visible.sync="dialogVisible" width="40%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="任务内容" prop="data">
          <el-input v-model="ruleForm.data" placeholder="请输入任务内容" type="textarea" :autosize="{ minRows: 3 }"></el-input>
        </el-form-item>
        <el-form-item label="时间" required>
          <el-col :span="24">
            <el-form-item prop="setTime">
              <el-date-picker type="datetime" placeholder="选择时间" v-model="ruleForm.setTime"
                value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import DataItem from './components/DataItem'
import OrderChart from './components/chart/OrderChart'
import SalesChart from './components/chart/SalesChart'
import StudentChart from './components/chart/StudentChart'
import EnrollmentChannelsChart from './components/chart/EnrollmentChannelsChart'
import DepartmentChart from './components/chart/DepartmentChart'
import SchoolChart from './components/chart/SchoolChart'
import FullYearSalesChart from './components/chart/FullYearSalesChart'
import StackAvatar from '@/components/common/StackAvatar'
import ResizeMixin from '@/mixins/ResizeMixin'

import api from "@/api/login"

import { formatDate, getCurDay } from '../../utils/MyTools'
export default {
  name: 'Main',
  components: {
    DataItem,
    OrderChart,
    SchoolChart,
    SalesChart,
    StudentChart,
    EnrollmentChannelsChart,
    DepartmentChart,
    FullYearSalesChart,
    StackAvatar
  },
  mixins: [ResizeMixin],
  data() {
    return {
      ruleForm: {
        data: '',
        setTime: '',
        finish: 0
      },
      rules: {
        data: [
          { required: true, message: '请输入任务内容', trigger: 'blur' },
        ],
        // setTime: [
        //   { required: true, message: '请选择时间', trigger: 'blur' },
        // ],
      },
      timrRange: [],
      timrRange3: [],
      timrRange4: [],
      inputValue0: "",
      inputValue1: "",
      inputValue2: "",
      inputValue3: "",
      inputValue4: "",
      inputValue5: "",
      inputValue6: "",
      agentCount0: 0,
      completeCount0: 0,
      agentCount1: 0,
      completeCount1: 0,
      agentCount2: 0,
      completeCount2: 0,
      agentCount3: 0,
      completeCount3: 0,
      agentCount4: 0,
      completeCount4: 0,
      agentCount5: 0,
      completeCount5: 0,
      agentCount6: 0,
      completeCount6: 0,
      dataList: [
        {
          id: 1,
          title: '今日访问量',
          data: '+1000',
          bottomTitle: '总访问量',
          totalSum: '100万+',
          extra: {
            data: 1000,
            data1: 2350
          }
        },
        {
          id: 2,
          title: '新增用户',
          data: '+500',
          bottomTitle: '总用户量',
          totalSum: '200万+',
          extra: {
            data: 700,
            data1: 968
          }
        },
        {
          id: 3,
          title: '当月销售额',
          data: '￥50000',
          bottomTitle: '累计销售额',
          totalSum: '2000万+',
          extra: {
            data: 80
          }
        },
        // {
        //   title: '当月订单量',
        //   data: '189笔',
        //   bottomTitle: '累计订单量',
        //   totalSum: '1万+',
        //   extra: {
        //     data: 80
        //   }
        // }
      ],
      stateNum: 0,
      endNum: 0,
      nowDateTime: "",
      weeks: [
        '时段', '周一', '周二', '周三', '周四', '周五', '周六', '周日',
      ],
      todayDate: '',
      months: [],
      curDate: '',
      nowDate: new Date(),
      isFirstDayOfMondayOrSunday: 1,
      dayWeekTimes: [],
      dialogVisible: false,
      dialogVisibleTitle: "",
      type: 0,
      getCurDayList: [],
      num1: 0,
      num2: 0

    }
  },
  computed: {
    collapse() {
      return this.$layoutStore.state.isCollapse
    }
  },
  mounted() {
    this.getCurWeek();
    this.getqueryByDate();
    this.getWeekTimeAsk();

  },
  watch: {
    collapse(newVal) {
      setTimeout(() => {
        this.onResize()
      }, 500)
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          api.saveSchedule(this.ruleForm).then(res => {
            if (res.code == 200) {
              this.$message.success('操作成功');
              this.getqueryByDate();
              this.getWeekTimeAsk();
            }
            this.dialogVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getqueryByDate() {
      let data = {
        setTime: this.getNowDate()
      }
      this.num1 = 0;
      this.num2 = 0;
      api.queryByDate(data).then(res => {
        if (res.code == 200) {
          this.getCurDayList = res.data.calendars
          for (let i = 0; i < this.getCurDayList.length; i++) {
            if (this.getCurDayList[i].finish == 1) {
              this.num1++;
            } else {
              this.num2++;
            }
          }
        }
      })
    },
    getWeekTimeAsk() {
      api.getWeekTimeAsk(this.type).then(res => {
        for (let i = 0; i < this.months.length; i++) {
          if (res.data.calendars[this.months[i].date]) {
            this.months[i].weekDayAsk = res.data.calendars[this.months[i].date]
          }else{
            this.months[i].weekDayAsk=[];
          }
        }


      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getCurWeek() {
      // const { year, month, day } = formatDate(new Date());
      // const dateObj = {
      //   date: `${year}-${month}-${day}`,
      //   timestamp: new Date(`${year}-${month}-${day}`).getTime()
      // }
      this.dealDate(new Date())

    },
    /**
     * 显示当天日期状态
     * @param date
     */
    dealDate(date) {
      this.months = ['']
      this.getWeek(date)
      const curDate = getCurDay()
      this.months.forEach(item => {
        item.isCurDate = item.date === curDate
      })
    },
    /**
   * 处理日期
   * @param date
   * @param n
   * @returns {*}
   */
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    /**
 * 获取 时间
 * @param time
 */
    getWeek(time) {

      this.curDate = new Date(time)
      //当前是周几
      const whichDay = time.getDay()
      let num = 0
      let weekStr = "星期六/日"
      let str1 = ""
      let str2 = ""
      if (this.isFirstDayOfMondayOrSunday <= whichDay) {
        num = this.isFirstDayOfMondayOrSunday
      } else {
        num = this.isFirstDayOfMondayOrSunday - 7
      }
      const weekDay = time.getDay() - num
      time = this.addDate(time, weekDay * -1)
      for (let i = 0; i < 7; i++) {
        const { year, month, day, week } = formatDate(i === 0 ? time : this.addDate(time, 1))
        if (i == 5) {
          str1 = "星期六"
        } else if (i == 6) {

          str2 = "日"
          this.months.push({
            date: `${year}-${month}-${day}`,
            showDate: `${month}-${day}`,
            timestamp: new Date(`${year}-${month}-${day}`).getTime(),
            week: str1 + "/" + str2,
            weekDay: weekStr + "(" + (str1 + "-" + str2) + ")",
            weekDayAsk: [
            ]
          })
        } else {
          // if (i == 3) {
          //   this.months.push({})
          // }
          this.months.push({
            date: `${year}-${month}-${day}`,
            showDate: `${month}-${day}`,
            timestamp: new Date(`${year}-${month}-${day}`).getTime(),
            week: week,
            weekDay: week + "(" + (month + "/" + day) + ")",
            weekDayAsk: [

            ]
          })
        }

      }
      this.months.sort((a, b) => a.timestamp - b.timestamp)

      delete this.months[0]
      this.todayDate = `${this.months[1].date} ~ ${this.months[this.months.length - 1].date}`
      this.months.splice(0, 1);
    },
    /**
       * 上周
       */
    getLastWeek() {
      this.type = -1
      const date = this.addDate(this.curDate, -7)
      // { year, month, day } = formatDate(date),
      // dateObj = {
      //   date: `${year}-${month}-${day}`,
      //   timestamp: new Date(`${year}-${month}-${day}`).getTime()
      // }
      this.dealDate(date)
      this.getWeekTimeAsk();
      // this.$emit('changeWeek', dateObj)
    },
    /**
     * 本周
     */
    getCurWeek() {
      this.type = 0;
      // const { year, month, day } = formatDate(new Date()),
      //   dateObj = {
      //     date: `${year}-${month}-${day}`,
      //     timestamp: new Date(`${year}-${month}-${day}`).getTime()
      //   }
      this.dealDate(new Date())
      this.getWeekTimeAsk();
      // this.$emit('changeWeek', dateObj)
    },
    /**
     * 下周
     */
    getNextWeek() {
      this.type = 1;
      const date = this.addDate(this.curDate, 7)
      // { year, month, day } = formatDate(date),
      // dateObj = {
      //   date: `${year}-${month}-${day}`,
      //   timestamp: new Date(`${year}-${month}-${day}`).getTime()
      // }
      this.dealDate(date)
      this.getWeekTimeAsk();
      // this.$emit('changeWeek', dateObj)
    },
    ///点击添加急事
    addEvent(val) {
      switch (val) {
        case 0:
          var data = {
            data: this.inputValue0,
            setTime: this.months[val].date
          }
          this.agentCount0++;
          break;
        case 1:
          var data = {
            data: this.inputValue1,
            setTime: this.months[val].date
          }
          this.agentCount1++;


          break;
        case 2:
          var data = {
            data: this.inputValue2,
            setTime: this.months[val].date
          }
          this.agentCount2++;
          break;
        case 3:
          var data = {
            data: this.inputValue3,
            setTime: this.months[val].date
          }
          this.agentCount3++;
          break;
        case 4:
          var data = {
            data: this.inputValue4,
            setTime: this.months[val].date
          }
          this.agentCount4++;
          break;
        case 5:
          var data = {
            data: this.inputValue5,
            setTime: this.months[val].date
          }
          this.agentCount5++;
          break;
        default:
          break;
      }
      api.saveSchedule(data).then(res => {
        this.getWeekTimeAsk();

      })

      // this.months[val].weekDayAsk.push(obj);
    },
    del(val, id) {
      api.deleteById(id).then(res => {
        if (res.code == 200) {
          this.$message.success('操作成功');
        }
        this.getqueryByDate();
        this.getWeekTimeAsk();
      })
      // this.months[val].weekDayAsk.splice(val2, 1);
      // switch (val) {
      //   case 0:
      //     this.agentCount0--;
      //     break;
      //   case 1:
      //     this.agentCount1--;
      //     break;
      //   case 2:
      //     this.agentCount2--;
      //     break;
      //   case 3:
      //     this.agentCount3--;
      //     break;
      //   case 4:
      //     this.agentCount4--;
      //     break;
      //   case 5:
      //     this.agentCount5--;
      //     break;
      //   default:
      //     break;
      // }
    },
    edit(val, val2) {
      var data = {
        id: val2,
        finish: 1


      }
      api.editCalendar(data).then(res => {
        if (res.code == 200) {
          this.$message.success('操作成功');
        }
        this.getqueryByDate();
        this.getWeekTimeAsk();
      })
      // this.months[val].weekDayAsk[val2].status = 2
      // switch (val) {
      //   case 0:
      //     this.completeCount0++;
      //     this.agentCount0--;
      //     break;
      //   case 1:
      //     this.completeCount1++;
      //     this.agentCount1--;
      //     break;
      //   case 2:
      //     this.completeCount2++;
      //     this.agentCount2--;

      //     break;
      //   case 3:
      //     this.completeCount3++;
      //     this.agentCount3--;
      //     break;
      //   case 4:
      //     this.completeCount4++;
      //     this.agentCount4--;

      //     break;
      //   case 5:
      //     this.completeCount5++;
      //     this.agentCount5--;
      //     break;
      //   default:
      //     break;
      // }
    },
    getNowDate() {
      var myDate = new Date;
      var year = myDate.getFullYear(); //获取当前年
      var mon = this.formatNumber(myDate.getMonth() + 1); //获取当前月
      var date = this.formatNumber(myDate.getDate()); //获取当前日
      var hours = this.formatNumber(myDate.getHours()); //获取当前小时
      var minutes = this.formatNumber(myDate.getMinutes()); //获取当前分钟
      var seconds = this.formatNumber(myDate.getSeconds()); //获取当前秒
      var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
      return now;
    },
    formatNumber(index) {
      return index = index < 10 ? "0" + index : index;
    },
    addTask() {
      this.dialogVisibleTitle = "添加任务";
      this.dialogVisible = true;
    },
    onResize(width) {
      // this.$refs.mOrderChart[0].updateChart()
      // this.$refs.salesChart.updateChart()
      // this.$refs.departmentChart.updateChart()
      // this.$refs.enrollmentChannelsChart.updateChart()
      // this.$refs.schoolChart.updateChart()
      // this.$refs.studentChart.updateChart()
      // this.$refs.fullYearSalesChart.updateChart()
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

@media screen and (max-width: 992px) {
  .item-wrapper {
    margin-bottom: 5px;
  }

  .map-margin-tb {
    margin: 5px 0;
  }
}

.chart-item {
  background-color: #fff;
}

.stack-avatar-wrapper {
  position: absolute;
  right: -2%;
  top: 10%;
}
</style>
